#!/bin/bash
set -o errexit  \
    -o nounset  \
    -o pipefail

function build_local_image()
{
  # ${1} -> directory
  # ${2} -> tag
  pushd "${1}"

  docker build -t "${2}" .

  popd
}

# ${1} -> product
build_local_image "${1}" "influxdb-test"

read -d '' -r PROGRAM <<'PROGRAMEOF' || true
set -o errexit  \
    -o nounset  \
    -o pipefail \
    -o xtrace

export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install --yes binutils

function test_race()
{
  # ${1} -> target
  if grep --quiet 'WARNING\: DATA RACE' <<<"$(strings "${1}")"
  then
    printf 'Race-enabled binary detected: %s\n' "${1}" >&2 ; exit 1
  fi
}

function test_static_pie()
{
  # ${1} -> target
  NEEDED="$(readelf -d "${1}" | (grep 'NEEDED' || true ))"

  # shellcheck disable=SC2181
  if [[ ${?} -ne 0 ]]
  then
    cat <<'EOF'
ERROR: readelf could not analyze the influxd executable! This
       might be the consequence of installing a package built
       for another platform OR invalid compiler/linker flags.
EOF
    exit 2
  fi

  if [[ "${NEEDED:-}" ]]
  then
    cat <<'EOF'
ERROR: influxd not statically linked! This may prevent all
       platforms from running influxd without installing
       separate dependencies.
EOF
    exit 2
  fi

  PIE="$(readelf -d "${1}" | (grep 'Flags: PIE' || true))"
  if [[ ! "${PIE:-}" ]]
  then
    # TODO(bnpfeife): Exit with error.
    #
    # Changes to the compiler options since the last update have made all
    # binaries "static-pie". However, some versions of InfluxDB 1.X OSS
    # do not have these changes.
    printf 'ERROR: ${1} not linked with "-fPIE"!\n'
  fi
}

for target in             \
  /usr/bin/influx         \
  /usr/bin/influx_inspect \
  /usr/bin/influxd        \
  /usr/bin/influxd-ctl    \
  /usr/bin/influxd-meta
do
  if [[ -x "${target}" ]]
  then
    test_race "${target}"
    test_static_pie "${target}"
  fi
done
PROGRAMEOF

docker run -it "influxdb-test" bash -c "${PROGRAM}"
